<?php

class Category_Model extends Model {

    public static $CATEGORY_TABLE = "category";

    public static $FLD_CATEGORY_ID = "id";

    public static $FLD_CATEGORY_NAME = "name";

    public function __construct() {
        parent::__construct();
    }

    public function get() {
        $arr = $this -> db -> select('SELECT * FROM ' . $this::$CATEGORY_TABLE);
        return json_encode($arr);
    }
    
    public function find( $id)
    {
        $arr = $this -> db -> select('SELECT * FROM ' . $this::$CATEGORY_TABLE." WHERE id=$id");
        return isset($arr[0]) ? $arr[0] : null;
    }
    
    public function getSchema( $name)
    {
        return json_encode($this->db->select("SHOW COLUMNS FROM c_".$name));
    }

    public function create() {
        $form = new Form();
        try {
            $form   -> post('name')
                        ->val('minlength', 3)
                        ->val('maxlength', 22)
                        ->fixSpace()
                        ->val('withUnderScore')
                    -> post('size');
            
            for ($i=1; $i <= $form->fetch('size'); $i++) { 
                $form -> post('fld_'.$i)
                        ->val('minlength', 3)
                        ->val('maxlength', 22)
                        ->fixSpace()
                        ->val('withUnderScore')
                      -> post('type_'.$i);
            }        
            
            $form->submit();
        } catch (Exception $e) {
            return $e -> getMessage();
        }
        $data = $form -> fetch();
        
        //create fileds for table
        $fields = array();
        for ($i=1; $i <= $data['size']; $i++)
        {
            if ( isset($data['fld_'.$i]))
            {
                $name = $data['fld_'.$i];
                $type = $data['type_'.$i];
                $fields[$name] = $type;
            }
               
        }
        $table = 'c_'.$data['name'];
        $this->db->create($table, $fields);
        $category['name'] = $data['name'];
        $this->db->insert('category', $category);
    }

    public function drop( $name)
    {
        $this->db->select('DROP TABLE c_'.$name);
    }

    public function delete( $id)
    {
        $table = $this->find($id);
        $this->db->delete('category', "id=$id");
        $this->drop($table['name']);
    }

}
